<?php
/**
 * 文件上传类
 * @author pan.liang
 */
include_once dirname(dirname(__FILE__))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
class m_upload extends m_config
{
    // 令牌保存目录
    public static $dir_token_path = null;
    public static $dir_file_path = null;
    // 上传文件保存目录
    
    public static $arr_params = null;

    public static function init($arr_params,$dir_file_path)
    {
        $result_check = self::check_params($dir_file_path,$arr_params);
        if($result_check['ret'] !=0)
        {
            return $result_check;
        }
        $str_action = $arr_params['action'];
        return self::$str_action();
    }
    
    /**
     * 参数验证
     */
    public static function check_params($dir_file_path,$arr_params = null)
    {
        if(!isset($arr_params['action']) || strlen($arr_params['action']) <1)
        {
            return self::return_data(1,'action为空');
        }
        $str_action = $arr_params['action'];
        self::$dir_token_path = dirname(dirname(dirname(__FILE__)))."/data/temp/uploads/tokens/";
        self::$dir_file_path = trim(rtrim(rtrim($dir_file_path,'/'),'\\'));
        self::$arr_params = $arr_params;
        if(strlen(self::$dir_file_path) <1)
        {
            return self::return_data(1,'文件存储地址为空');
        }
        $result = self::make_dir_out_project(self::$dir_file_path);
        if($result['ret'] !=0)
        {
            return $result;
        }
        if(strlen(self::$dir_token_path) <1)
        {
            return self::return_data(1,'文件token地址为空');
        }
        $result = self::make_dir_out_project(self::$dir_token_path);
        if($result['ret'] !=0)
        {
            return $result;
        }
        if(!in_array($str_action, array('get_token','upload_file')))
        {
            return self::return_data(1,'不存在此方法'.$str_action);
        }
        return self::return_data(0,'ok'.$str_action);
    }
    
    /**
     * 获取令牌
     */
    public static function get_token()
    {
        $token_id = md5(self::$dir_file_path);
        $pathInfo = pathinfo(self::$arr_params['name']);
        $file = array(
            // 上传文件名称
            'name'=>self::$arr_params['name'],
            // 上传文件总大小
            'size'=>self::$arr_params['size'],
            // 上传文件TOKENID
            'token'=>$token_id,
            // 上传文件的修改日期
            'modified'=>self::$arr_params['modified'],
            // 上传文件保存目录
            'filePath'=>self::$dir_file_path,
            // 已上传文件大小
            'up_size'=>0,
            //硬盘信息
            'diskid'=>self::$arr_params['diskid'],
        );
        if(file_exists(self::$dir_file_path))
        {
            $file['success'] = false;
            return self::return_data(1,'error',self::make_encode($file,1));
//             @unlink(self::$dir_file_path);
        }
        // 判断是否存在该令牌信息
        if (! file_exists(self::$dir_token_path . $token_id . '.token'))
        {
            // 保存令牌信息
            $result_set_token = self::setTokenInfo($file['token'], $file);
            if($result_set_token['ret'] !=0)
            {
                return $result_set_token;
            }
        }
        $file['success'] = true;
        return self::return_data(0,'ok',self::make_encode($file,1));
    }

    /**
     * 上传接口
     */
    public static function upload_file()
    {
        if ('html5' == self::$arr_params['client'])
        {
            return self::html5Upload();
        }
        return self::return_data(0,'暂时不支持'.self::$arr_params['client'],array('success'=>false));
    }

    public static function make_encode($array,$type=1)
    {
        if(!is_array($array) || empty($array))
        {
            return array();
        }
        $last_data = array();
        foreach ($array as $key=>$value)
        {
            if($key == 'token' || $key=='success')
            {
                $last_data[$key] = $value;
            }
            else
            {
                $last_data[$key] = ($type == 1) ? base64_encode($value) : base64_decode($value);
            }
        }
        return $last_data;
    }
    

    /**
     * HTML5上传
     */
    public static function html5Upload()
    {
        $token = self::$arr_params['token'];
        $fileInfo = self::getTokenInfo($token);
        if($fileInfo['ret'] !=0)
        {
            return $fileInfo;
        }
        $fileInfo = $fileInfo['data_info'];
        if ($fileInfo['size'] <= $fileInfo['up_size'])
        {
            $fileInfo['success'] = true;
            return self::return_data(0,'ok',$fileInfo);
        }
        // 取得上传内容
        $data = file_get_contents('php://input', 'r');
        if (! empty($data))
        {
            // 上传内容写入目标文件
            $fp = fopen($fileInfo['filePath'], 'a');
            flock($fp, LOCK_EX);
            fwrite($fp, $data);
            flock($fp, LOCK_UN);
            fclose($fp);
            // 累积增加已上传文件大小
            $fileInfo['up_size'] += strlen($data);
            if ($fileInfo['size'] <= $fileInfo['up_size'])
            {
                // 上传完成后删除令牌信息
                @unlink(self::$dir_token_path . $token . '.token');
                $fileInfo['success'] = true;
                $fileInfo['start'] = $fileInfo['up_size'];
                return self::return_data(0,'ok',$fileInfo);
            }
            $set_token = self::setTokenInfo($token, $fileInfo);
            if($set_token['ret'] !=0)
            {
                $fileInfo['success'] = false;
                $fileInfo['start'] = $fileInfo['up_size'];
                return self::return_data(0,'ok',$fileInfo);
            }
        }
        $fileInfo['success'] = true;
        $fileInfo['start'] = $fileInfo['up_size'];
        return self::return_data(0,'ok',$fileInfo);
    }

    /**
     * 生成文件内容
     */
    public static function setTokenInfo($token, $data)
    {
        $data = is_array($data) ? $data : array();
        $data = self::make_encode($data,1);
        $result = @file_put_contents(self::$dir_token_path . $token . '.token', json_encode($data));
        return $result ? self::return_data(0,'Ok') : self::return_data(1,'保存TOKEN失败');
    }

    /**
     * 获取文件内容
     */
    public static function getTokenInfo($token)
    {
        $file = self::$dir_token_path . $token . '.token';
        $content = null;
        if (!file_exists($file))
        {
            return self::return_data(1,'获取TOKEN文件不存在了');
        }
        $str_content = file_get_contents($file);
        if(!self::is_json($str_content))
        {
            return self::return_data(1,'获取的内容非json');
        }
        $content = json_decode($str_content, true);
        $content = is_array($content) ? $content : null;
        $content = self::make_encode($content,2);
        return self::return_data(0,'ok',$content);
    }
}